<template>
  <el-dialog
      :title="detailTitle"
      :visible.sync="visible"
      width="80%"
      center
      @close="handleClose"
  >
    <el-container>
      <el-main style="background: #f8f9fa; padding: 20px;">
        <el-card body-style="padding: 30px;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          </div>

          <!-- 基础信息 -->
          <h3 style="font-size: 18px; font-weight: 500; margin-bottom: 16px;">基础信息</h3>
          <el-descriptions title="" border :column="3" style="margin-bottom: 24px;">
            <!-- 第一行 -->
            <el-descriptions-item label="发文日期">{{ doc.createDate | dateFormat }}</el-descriptions-item>
            <el-descriptions-item label="发文单位">{{ doc.senderOrg || '无' }}</el-descriptions-item>

            <!-- 第二行 -->
            <el-descriptions-item label="密级">{{ doc.secretLevel || '普通' }}</el-descriptions-item>

            <!-- 第三行 -->
            <el-descriptions-item label="紧急程度">{{ doc.urgencyLevel || '普通' }}</el-descriptions-item>

            <!-- 第四行 -->
            <el-descriptions-item label="文件页数">{{ doc.pageCount || '无' }}</el-descriptions-item>
            <el-descriptions-item label="文件标题">{{ doc.title || '无' }}</el-descriptions-item>

            <!-- 第五行 -->
            <el-descriptions-item label="来文编号">{{ doc.senderDocNo || '无' }}</el-descriptions-item>
            <el-descriptions-item label="限时反馈">{{ doc.feedbackRequired ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="限办时间">{{ doc.limitDate }}</el-descriptions-item>

            <!-- 第六行 -->
            <el-descriptions-item label="处理类型">{{ doc.processType || '无' }}</el-descriptions-item>
            <el-descriptions-item label="归档日期">{{ doc.archiveDate | dateFormat }}</el-descriptions-item>

            <!-- 第七行 -->
            <el-descriptions-item label="密件类型">{{ doc.secretType === 1 ? '密件' : '普通件' }}</el-descriptions-item>
            <el-descriptions-item label="当前状态">{{ getStatusText(doc.status) }}</el-descriptions-item>

            <el-descriptions-item label="件号">{{ doc.fileNo }}</el-descriptions-item>
            <el-descriptions-item label="办件单位">{{ doc.handlingOrg || '无' }}</el-descriptions-item>
          </el-descriptions>

          <!-- 附件信息 -->
          <div style="margin-top: 24px; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 500; margin-bottom: 16px;">附件</h3>
            <el-table :data="attachments" style="width: 100%;" border>
              <el-table-column label="文件名称" prop="fileName"></el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button
                      type="text"
                      size="small"
                      @click="previewAttachment(row)"
                      :disabled="!row.filePath || row.loading">
                    {{ row.loading ? '加载中...' : '查看' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="attachments.length === 0" style="text-align: center; padding: 20px; color: #909399;">
              暂无附件
            </div>
          </div>

          <!-- 流转意见 -->
          <div style="margin-top: 24px;">
            <h3 style="font-size: 18px; font-weight: 500; margin-bottom: 16px;">审批流转记录</h3>
            <el-timeline>
              <!-- 审批意见时间线 -->
              <el-timeline-item
                  v-for="(opinion, index) in doc.opinions"
                  :key="opinion.id || index"
                  :timestamp="opinion.createDate"
                  :type="getTimelineType(opinion.level)"
              >
                <div style="padding: 20px; background: #f8f9fa; border-radius: 8px;">
                  <div style="font-size: 16px; font-weight: 500; margin-bottom: 10px;">
                    {{ getOpinionTitle(opinion.level) }}
                  </div>
                  <p style="color: #606266;">{{ opinion.opinion || '无具体意见' }}</p>
                  <div style="font-size: 12px; color: #909399; margin-top: 8px;">
                    处理人：{{ opinion.name || '未知' }} ({{ opinion.position || '无职位' }})
                  </div>
                  <div style="font-size: 12px; color: #909399; margin-top: 8px;">
                    录入人：{{ opinion.recorderName || '系统自动录入' }}
                  </div>
                </div>
              </el-timeline-item>

              <!-- 当前处理人独立时间线节点 -->
              <el-timeline-item
                  v-if="hasCurrentHandler"
                  :timestamp="''"
                  type="warning"
                  style="margin-top: 10px;"
              >
                <div style="padding: 20px; background: #f8f9fa; border-radius: 8px; display: flex; align-items: center;">
                  <div style="font-size: 16px; font-weight: 500; color: #d63031;">
                    当前流转至：{{ currentHandler }}
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
export default {
  name: "OutgoingDetailDialog",
  props: {
    visible: Boolean,
    docId: [String, Number]
  },
  data() {
    return {
      doc: {},
      attachments: [],
      flowObjects: []
    };
  },
  computed: {
    detailTitle() {
      return '发文详情';
    },
    getTimelineType() {
      return (level) => {
        const typeMap = {1: 'primary', 2: 'success', 3: 'info', default: 'default'};
        return typeMap[level] || typeMap.default;
      };
    },
    getOpinionTitle() {
      return (level) => {
        const titleMap = {1: '主要领导意见：', 2: '分管领导意见：', 3: '部门意见：', default: '办公室拟办意见：'};
        return titleMap[level] || titleMap.default;
      };
    },
    currentHandler() {
      if (!this.doc.opinions || this.doc.opinions.length === 0) return '';
      const lastOpinion = this.doc.opinions[this.doc.opinions.length - 1];
      return lastOpinion.nextObjectId
          ? this.getNextHandler(lastOpinion.nextObjectId)
          : '无后续流转';
    },
    hasCurrentHandler() {
      if (!this.doc.opinions || this.doc.opinions.length === 0) return false;
      const lastOpinion = this.doc.opinions[this.doc.opinions.length - 1];
      return !!lastOpinion.nextObjectId;
    }
  },
  watch: {
    // 添加对visible的监听，避免在不可见时加载数据
    visible: {
      immediate: true,
      handler(val) {
        if (val && this.docId) {
          this.loadDoc();
        }
      }
    },
    // 修改docId的监听逻辑
    docId: {
      immediate: true,
      handler(newVal) {
        // 只有当对话框可见时才加载
        if (this.visible && newVal) {
          this.loadDoc();
        }
      }
    }
  },
  filters: {
    dateFormat(date) {
      if (!date) return '无';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    }
  },
  methods: {
    loadDoc() {
      if (!this.docId) return;

      this.$request.get(`/outgoingDoc/${this.docId}`)
          .then(res => {
            if (res.code === '200') {
              this.doc = res.data;
              this.loadAttachments(this.docId);
            } else {
              this.$message.error('加载文档失败：' + res.msg);
            }
          })
          .catch(err => {
            console.error('加载文档请求失败:', err);
            this.$message.error('网络请求失败，请重试');
          });
    },

    loadAttachments(docId) {
      this.$request.get('/attachments/preview', {
        params: {
          docId: docId,
          fileType: 'out'
        }
      }).then(res => {
        if (res.code === '200') {
          this.attachments = res.data.map(item => ({
            ...item,
            loading: false
          }));
        } else {
          this.$message.error('加载附件失败：' + res.msg);
        }
      });
    },

    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '流转中',
        2: '已存档'
      };
      return statusMap[status] || '未知状态';
    },

    getNextHandler(nextObjectId) {
      if (!nextObjectId) return '无后续流转';
      if (!this.flowObjects || this.flowObjects.length === 0) return '未知处理人';

      const obj = this.flowObjects.find(o => o.id === nextObjectId);
      return obj ? `${obj.name} (${obj.position})` : '未知处理人';
    },

    // 预览附件
    async previewAttachment(attachment) {
      if (!attachment.filePath) {
        this.$message.warning('附件路径无效');
        return;
      }

      attachment.loading = true;
      let fileName = attachment.filePath.split('/').pop();

      try {
        // 添加 responseType: 'blob' 参数
        const response = await this.$request.get(`/files/preview/${fileName}`, {
          responseType: 'blob',  // 关键参数
          onDownloadProgress: progressEvent => {
            // 显示加载进度
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
            this.$set(attachment, 'progress', percent);
          }
        });

        // Blob URL
        const mimeType = response.headers['content-type'] || 'application/pdf';

        // 创建类型化Blob对象
        const blob = new Blob([response.data], { type: mimeType });
        const blobUrl = URL.createObjectURL(blob);

        // 直接在新窗口打开Blob URL
        window.open(blobUrl, '_blank');

      } catch (error) {
        console.error('预览失败:', error);
        this.$message.error('文件加载失败');
      } finally {
        attachment.loading = false;
      }
    },

    handleClose() {
      this.$emit('close');
    }
  },
  mounted() {
    // 加载流转对象
    this.$request.get('/flowObject/all')
        .then(res => {
          if (res.code === '200') {
            this.flowObjects = res.data;
          }
        });
  }
};
</script>

<style scoped>
/* 样式保持不变 */
</style>
